<?php
    /*
    Plugin Name: Jonsomnia Development - Gravity Forms AWeber Integration
    Plugin URI: http://www.jonsomnia.com
    Description: Add options for creating an opt-in form for your AWeber account with Gravity Forms.
    Author: J. Wisdom
    Version: 0.1
    Author URI: http://www.jonsomnia.com
    */
    //define('WP_DEBUG', true);
    if(!class_exists('GFormsAWeberIntegration')) {
	    class GFormsAWeberIntegration {
	
			/**
			 * Current version of the plugin
			 **/
			var $version = '0.1';
	
			/**
			 * PHP4 constructor
			 **/
			function GFormsAWeberIntegration() {
				__construct();
			}
	
			/**
			 * PHP5 constructor
			 **/
			function __construct() {
				//add_action('admin_menu', array(&$this, 'admin_page'));
				//add_action('network_admin_menu', array(&$this, 'network_admin_page'));
				add_action('wp_print_scripts', array(&$this, 'enqueueJS'));
				add_action('wp_print_styles', array(&$this, 'enqueueCSS'));
				add_action('gform_properties_settings', array(&$this, 'addAWeberSettings'), 10, 2);
				add_action('gform_form_settings_before_save', array(&$this, 'saveAWeberSettings'));
				add_action('gform_editor_js', array(&$this, 'aWeberSettingsScripts'));
				add_filter('gform_tooltips', array(&$this, 'aWeberSettingsTooltips'));
				add_action('gform_after_submission', array(&$this, 'addAWeberContact'));
				add_action('gform_field_advanced_settings', array(&$this, 'aWeberAdvancedSettings'), 10, 2);
				add_action('gform_properties_settings', array(&$this, 'addAWeberSettings'), 10, 2);
				$this->requireClasses();
			}
			
			function saveAWeberSettings() {
				
			}
			
			function aWeberAdvancedSettings($position, $form_id) {
				if($position == 50){
				?>			
			        <li class="aweberemail_setting field_setting">
			            <label for="field_admin_label">
			                <?php _e("Aweber Email", "gravityforms"); ?>
			                <?php gform_tooltip("form_field_aweberemail_value") ?>
			            </label>
			            <input type="checkbox" id="field_aweberemail_value" onclick="SetFieldProperty('aweberEmailField', this.checked);" /> use as AWeber e-mail.
			        </li>
			        <li class="awebername_setting field_setting">
			            <label for="field_name_label">
			                <?php _e("Aweber Name", "gravityforms"); ?>
			                <?php gform_tooltip("form_field_awebername_value") ?>
			            </label>
			            <input type="checkbox" id="field_awebername_value" onclick="SetFieldProperty('aweberNameField', this.checked);" /> use as AWeber name.
			        </li>
				<?php
				}
			}
			
			
			
			function aWeberSettingsScripts() {
				?>
					<script type='text/javascript'>
				        //adding setting to fields of type "text"
				        
				        fieldSettings["email"] += ", .aweberemail_setting";
				        fieldSettings["name"] += ", .awebername_setting";
				        //fieldSettings[""]
				        //binding to the load field settings event to initialize the checkbox
				        jQuery(document).bind("gform_load_field_settings", function(event, field, form){
				        	
				            jQuery("#field_aweberemail_value").attr("checked", field["aweberEmailField"] == true);
				            jQuery("#field_awebername_value").attr("checked", field["aweberNameField"] == true);
				            //jQuery("#form_aweberconsumerkey_value").attr(aweberConsumerKey
				            
				        });
				    </script>
				<?php
			}
			
			/***
			 **	addAWeberSettings
			 **  Add text boxes for the necessary inputs to integrate a form with an AWeber list.
			 ***/
			function addAWeberSettings($index, $form_id) {
				//If we're in the last property position of a form's settings add our HTML
				if($index == 500){
				   ?>
				   <li class="gform_setting_left_half">
				       <label for="field_admin_label" style="display: block;">
				           <?php _e("AWeber Consumer Key", "gravityforms"); ?>
				           <?php gform_tooltip("form_setting_aweber_consumer_key") ?>
				       </label>

				       <input type="text" id="form_aweberConsumerKey_input" onkeyup="UpdateFormProperty('aweberConsumerKey', this.value);" value="" />
				   </li>
				   <li class="gform_setting_right_half">
				       <label for="field_admin_label" style="display: block;">
				           <?php _e("AWeber Consumer Secret", "gravityforms"); ?>
				           <?php gform_tooltip("form_setting_aweber_consumer_secret") ?>
				       </label>
				       <input type="text" id="form_aweberconsumersecret_value" />
				   </li>
				   <li class="gform_setting_left_half">
				       <label for="field_admin_label" style="display: block;">
				           <?php _e("AWeber Access Key", "gravityforms"); ?>
				           <?php gform_tooltip("form_setting_aweber_access_key") ?>
				       </label>
				       <input type="text" id="form_aweberaccesskey_value" />
				   </li>
				   <li class="gform_setting_right_half">
				       <label for="field_admin_label" style="display: block;">
				           <?php _e("AWeber Access Secret", "gravityforms"); ?>
				           <?php gform_tooltip("form_setting_aweber_access_secret") ?>
				       </label>
				       <input type="text" id="form_aweberaccesssecret_value" />
				   </li>
				   <li class="gform_setting_left_half">
				       <label for="field_admin_label" style="display: block;">
				           <?php _e("AWeber Account ID", "gravityforms"); ?>
				           <?php gform_tooltip("form_setting_aweber_account_id") ?>
				       </label>
				       <input type="text" id="form_aweberaccountid_value" />
				   </li>
				   <li class="gform_setting_right_half">
				       <label for="field_admin_label" style="display: block;">
				           <?php _e("AWeber List ID", "gravityforms"); ?>
				           <?php gform_tooltip("form_setting_aweber_list_id") ?>
				       </label>
				       <input type="text" id="form_aweberlistid_value" />
				   </li>
				   <?php
				}		
			}
			
			
			/**
			 * aWeberSettingsTooltips adds the tooltips for our new settings fields.
			 **/
			function aWeberSettingsTooltips($tooltips) {
				$tooltips["form_setting_aweber_consumer_key"] = "<h6>Consumer Key</h6>Retrieve this from your AWeber application's settings.";
				$tooltips["form_setting_aweber_consumer_secret"] = "<h6>Consumer Secret</h6>Retrieve this from your AWeber application's settings.";
				$tooltips["form_setting_aweber_access_key"] = "<h6>Access Key</h6>Retrieve this from your AWeber application's settings.";
				$tooltips["form_setting_aweber_access_secret"] = "<h6>Access Secret</h6>Retrieve this from your AWeber application's settings.";
				$tooltips["form_setting_aweber_account_id"] = "<h6>Account ID</h6>Your AWeber Account ID.";
				$tooltips["form_setting_aweber_list_id"] = "<h6>List ID</h6>The AWeber list you would like form submissions opt-into.";
				$tooltips["form_field_aweberemail_value"] = "<h6>AWeber Email</h6>Should this field be used as the email for your AWeber opt-in?";
				$tooltips["form_field_awebername_value"] = "<h6>AWeber Name</h6>Should this field be used as the name for your AWeber opt-in?";
				return $toolstips;
			}
			
			function getFormMeta($formID, array $metaKeys) {
				global $wpdb;
				$metaValues = array();

				$sql = "SELECT display_meta AS Meta FROM {$wpdb->prefix}rg_form_meta WHERE form_id = " . $formID;
				$results = $wpdb->get_results($sql, OBJECT);
				$results = unserialize($results[0]->Meta);
				$results = $results['fields'];
				foreach($results as $result) {
					foreach($metaKeys as $key => $value) {
						if(array_key_exists($value, $result) && $result[$value] == "1")
							$metaValues[$value] = $result[$value];
					}
				}
				
				return $metaValues;
			}
			
			function updateFormMeta($formID, $metaValue) {
				global $wpdb;
				
				$wpdb->update(
					"{$wpdb->prefix}rg_form_meta",
					array('display_meta' => $metaValue),
					array('form_id' => $formID),
					array('%s'),
					array('%d')
				);
			}
			
			function addAWeberContact($form) {
				//print_r($this->getFormMeta($form['form_id'], array('aweberNameField', 'aweberEmailField')));
//				_e($this->getFormMeta($form['form_id']));
				//die();
				
				$contact = new AWeberContact();
				//die();
			}
			
			function enqueueJS() {
				if(is_admin()) {
					wp_register_script('AdminPlugin-JS', plugins_url('includes/js/adminCompile.js' , __FILE__), array('jquery'));
					wp_enqueue_script('AdminPlugin-JS');
				}
				else {
					wp_register_script('Plugin-JS', plugins_url('includes/js/plugin.js', __FILE__), array('Uniform-JS'));
					wp_enqueue_script('Plugin-JS');
				}
			}
			
			function enqueueCSS() {
				if(is_admin()) {
					wp_register_style('Admin-CSS', plugins_url('includes/css/admin.css', __FILE__));
					wp_enqueue_style('Admin-CSS');
				}
				else {
					wp_register_style('Plugin-CSS', plugins_url('includes/css/plugin.css', __FILE__));
					wp_enqueue_style('Plugin-CSS');
				}
			}
			
			function requireClasses() {
				foreach(glob(dirname(__FILE__) . '/includes/classes/*.php') as $class)
					require_once $class;	
			}

			/*//create the administrative page link
			function admin_page() {
				add_submenu_page('options-general.php', __('Category Carousel', 'category_carousel'), __('Category Carousel', 'category_carousel'), 'edit_pages', 'category-carousel', array(&$this, 'page_manage_plugin'));
			}
	
			//create the network admin page link for extra settings
			function network_admin_page() {
				add_submenu_page( 'settings.php', __( 'Category Carousel', 'category_carousel' ), __( 'Category Carousel', 'category_carousel' ), 'manage_network_options', 'category-carousel', array( &$this, 'page_network_admin' ) );
			}*/
		}
	}
	
	if(class_exists('GFormsAWeberIntegration'))
		$gfai &= new GFormsAWeberIntegration();
	
	if(!class_exists('AWeberConnect')) {
		class AWeberConnect {
			private $consumerKey    = 'AkeTke8nSjOW8muJMi0iwxVE'; # put your credentials here
			private $consumerSecret = 'd3AUfMAsLmO90UrKG6QvFtbE72sVRvaYD2nCbKJ3**'; # put your credentials here
			private $accessKey      = '***'; # put your credentials here
			private $accessSecret   = '***'; # put your credentials here
			private $account_id     = '***'; # put the Account ID here
			private $list_id        = '***'; # put the List ID here
			
			function __construct() {
				
			}
			
			function setConsumerKey($key) {
				$this->consumerKey = $key;
			}
			
			function setConsumerSecret($secret) {
				$this->consumerSecret = $secret;
			}
			
			function setAccessKey($key) {
				$this->accessKey = $key;
			}
			
			function setAccessSecret($secret) {
				$this->accessSecret = $secret;
			}
			
			function setAccountID($id) {
				$this->account_id = $id;
			}
			
			function setListID($id) {
				$this->list_id = $id;
			}
			
			function getConsumerKey() {
				return $this->consumerKey;
			}
			
			function getConsumerSecret() {
				return $this->consumerSecret;
			}
			
			function getAccessKey() {
				return $this->accessKey;
			}
			
			function getAccessSecret() {
				return $thos->accessSecret;
			}
			
			function getAccountID() {
				return $this->account_id;
			}
			
			function getListID() {
				return $this->list_id;
			}
		}
	}
	
	if(!class_exists('AWeberContact')) {
		class AWeberContact extends AWeberConnect {
			private $email;
			private $ip_address;
			private $ad_tracking;
			private $misc_notes;
			private $name;
			private $consumerKey    = 'AkCKYjMElOeZm7mI0y1mpeeB'; # put your credentials here
			private $consumerSecret = 'WMJoaMbQRDEUFccs1UPbnUDFHbTsMUBD67myzQAI'; # 
			private $requestToken = 'AqT9uFoPlkIy14icP02BGVrR ';
			private $tokenSecret = 'tk5quucF9fPvihN1BTdcgglzKEsitTEXgwxQBRAmFi';
			private $callbackURL = 'http://www.plugindev.com/?page_id=2';
			
			
			function __construct() {
			   # replace XXX with your real keys and secrets
			   $this->consumerKey = 'AkCKYjMElOeZm7mI0y1mpeeB';
			   $this->consumerSecret = 'WMJoaMbQRDEUFccs1UPbnUDFHbTsMUBD67myzQAI';
			   $this->accessToken = 'AgcyEE3sf7PobDNS5P4IJp2s';
			   $this->accessSecret = '6kqVehbSEzYRTw5xEBN1VTQOck9RYMuouNWfcqDE';
			   $this->account_id = '735195';
			   $this->list_id = '2758443';
			   $this->application = new AWeberAPI($this->consumerKey, $this->consumerSecret);
			   
			   try {

				    $account = $this->application->getAccount($this->accessToken, $this->accessSecret);
				    $listURL = "/accounts/{$this->account_id}/lists/{$this->list_id}";
				    $list = $account->loadFromUrl($listURL);
				//print_r($_POST);
				
				    # create a subscriber
				    $params = array(
				        'email' => $_POST['input_16'],
				        'name' => $_POST['input_1'] . ' ' . $_POST['input_2']
				    );
				    $subscribers = $list->subscribers;
				    $new_subscriber = $subscribers->create($params);
				} catch(AWeberAPIException $exc) {
				/*    print "<h3>AWeberAPIException:</h3>";
				  print " <li> Type: $exc->type              <br>";
				    print " <li> Msg : $exc->message           <br>";
				    print " <li> Docs: $exc->documentation_url <br>";
				    print "<hr>";
				    exit(1);*/
				}

			   
			}
			
			
			
			function setName($name) {
				$this->name = $name;
			}
			
			function setIP($address) {
				$this->ip_address = $address;
			}
			
			function setEmail($email) {
				$this->email = $email;
			}
			
			function setAdTracking($adTracking) {
				$this->adTracking = $adTracking;
			}
			
			function setNotes($notes) {
				$this->misc_notes = $notes;
			}
			
			function getName() {
				return $this->name;
			}
			
			function getEmail() {
				return $this->email;
			}
			
			function getAdTracking() {
				return $this->ad_tracking;
			}
			
			function getNotes() {
				return $this->misc_notes;
			}
			
			function getIP() {
				return $this->ip_address;
			}
			
			function pushUpdate() {
				
			}
		}
	}
?>